package com.googlecode.mylyn.ui;

import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;

public class GoogleCodeImages {

    private static ImageRegistry imageRegistry;

    private static final URL baseURL = GoogleCodeUiPlugin.getDefault().getBundle().getEntry("/icons/"); //$NON-NLS-1$

    public static final String T_ELCL = "elcl16"; //$NON-NLS-1$

    public static final String T_TOOL = "etool16"; //$NON-NLS-1$

    public static final String T_VIEW = "eview16"; //$NON-NLS-1$

    public static final ImageDescriptor OVERLAY_ENHANCEMENT = create(T_VIEW, "overlay-enhancement.gif"); //$NON-NLS-1$
    
    private static ImageDescriptor create(String prefix, String name) {
        try {
            return ImageDescriptor.createFromURL(makeIconFileURL(prefix, name));
        } catch (MalformedURLException e) {
            return ImageDescriptor.getMissingImageDescriptor();
        }
    }

    private static URL makeIconFileURL(String prefix, String name) throws MalformedURLException {
        if (baseURL == null) {
            throw new MalformedURLException();
        }

        StringBuffer buffer = new StringBuffer(prefix);
        if (prefix != "") { //$NON-NLS-1$
            buffer.append('/');
        }
        buffer.append(name);
        return new URL(baseURL, buffer.toString());
    }

    private static ImageRegistry getImageRegistry() {
        if (imageRegistry == null) {
            imageRegistry = new ImageRegistry();
        }

        return imageRegistry;
    }

    /**
     * Lazily initializes image map.
     */
    public static Image getImage(ImageDescriptor imageDescriptor) {
        ImageRegistry imageRegistry = getImageRegistry();
        Image image = imageRegistry.get("" + imageDescriptor.hashCode()); //$NON-NLS-1$
        if (image == null) {
            image = imageDescriptor.createImage();
            imageRegistry.put("" + imageDescriptor.hashCode(), image); //$NON-NLS-1$
        }
        return image;
    }
}
